﻿Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.IO
Imports System.Configuration
Imports System.Web.Security
Imports Ckeditor_Util
Imports Ckeditor_ImageMedia

Partial Public Class ImageBrowser
    Inherits Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            BindDirectoryList()
            ChangeDirectory(Nothing, Nothing)

            NewDirectoryButton.OnClientClick = "var name = prompt('Enter name of folder:'); if (name == null || name == '') return false; document.getElementById('" + NewDirectoryName.ClientID & "').value = name;"
        End If

        ResizeMessage.Text = ""
        Page.ClientScript.RegisterStartupScript(Me.[GetType](), "FocusImageList", "window.setTimeout(""document.getElementById('" + ImageList.ClientID & "').focus();"", 1);", True)
    End Sub

    Protected Sub BindDirectoryList()
        ImageFolder = ""
        Dim directories As String() = Directory.GetDirectories(FileImageFolder)
        directories = Array.ConvertAll(Of String, String)(directories, Function(directory__1 As String) directory__1.Substring(directory__1.LastIndexOf("\"c) + 1))
        DirectoryList.DataSource = directories
        DirectoryList.DataBind()
        DirectoryList.Items.Insert(0, "Root")
    End Sub

    Protected Sub ChangeDirectory(ByVal sender As Object, ByVal e As EventArgs)
        DeleteDirectoryButton.Enabled = (DirectoryList.SelectedIndex <> 0)
        ImageFolder = If((DirectoryList.SelectedIndex = 0), "", DirectoryList.SelectedValue + "/")
        SearchTerms.Text = ""
        BindImageList()
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub DeleteFolder(ByVal sender As Object, ByVal e As EventArgs)
        Directory.Delete(FileImageFolder, True)
        BindDirectoryList()
        ChangeDirectory(Nothing, Nothing)
    End Sub

    Protected Sub CreateFolder(ByVal sender As Object, ByVal e As EventArgs)
        Dim name As String = UniqueDirectory(NewDirectoryName.Value)
        Directory.CreateDirectory(FileImageFolderRoot & name)
        BindDirectoryList()
        DirectoryList.SelectedValue = name
        ChangeDirectory(Nothing, Nothing)
    End Sub

    Protected Sub BindImageList()
        ImageList.Items.Clear()
        Dim files As String() = Directory.GetFiles(FileImageFolder, "*" & SearchTerms.Text.Replace(" ", "*") & "*")
        files = Array.FindAll(files, Function(f As String) IsImage(f))

        For Each file As String In files
            If IsImage(file) Then
                ImageList.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1))
            End If
        Next

        If files.Length > 0 Then
            ImageList.SelectedIndex = 0
        End If
    End Sub

    Protected Sub Search(ByVal sender As Object, ByVal e As EventArgs)
        BindImageList()
    End Sub

    Protected Sub SelectImage(ByVal sender As Object, ByVal e As EventArgs)
        RenameImageButton.Enabled = (ImageList.Items.Count <> 0)
        DeleteImageButton.Enabled = (ImageList.Items.Count <> 0)
        ResizeImageButton.Enabled = (ImageList.Items.Count <> 0)
        ResizeWidth.Enabled = (ImageList.Items.Count <> 0)
        ResizeHeight.Enabled = (ImageList.Items.Count <> 0)

        If ImageList.Items.Count = 0 Then
            Image1.ImageUrl = ""
            ResizeWidth.Text = ""
            ResizeHeight.Text = ""
            Return
        End If

        Image1.ImageUrl = ImageFolder + ImageList.SelectedValue & "?" & New Random().[Next](1000)
        Dim img As Ckeditor_ImageMedia = Ckeditor_ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue))
        ResizeWidth.Text = img.Width.ToString()
        ResizeHeight.Text = img.Height.ToString()
        ImageAspectRatio.Value = "" & img.Width / CSng(img.Height)

        Dim pos As Integer = ImageList.SelectedItem.Text.LastIndexOf("."c)
        If pos = -1 Then
            Return
        End If
        RenameImageButton.OnClientClick = ("var name = prompt('Enter new filename:','" & ImageList.SelectedItem.Text.Substring(0, pos) & "'); if (name == null || name == '') return false; document.getElementById('") + NewImageName.ClientID & "').value = name + '" & ImageList.SelectedItem.Text.Substring(pos) & "';"
        OkButton.OnClientClick = "window.top.opener.CKEDITOR.dialog.getCurrent().setValueOf('info', 'txtUrl', encodeURI('" & ImageFolder & ImageList.SelectedValue.Replace("'", "\'") & "')); window.top.close(); window.top.opener.focus();"
    End Sub

    Protected Sub RenameImage(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String = UniqueFilename(NewImageName.Value)
        File.Move(FileImageFolder + ImageList.SelectedValue, FileImageFolder & filename)
        BindImageList()
        ImageList.SelectedValue = filename
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub DeleteImage(ByVal sender As Object, ByVal e As EventArgs)
        File.Delete(FileImageFolder + ImageList.SelectedValue)
        BindImageList()
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub ResizeWidthChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim ratio As Single = Parse(Of Single)(ImageAspectRatio.Value)
        Dim width As Integer = Parse(Of Integer)(ResizeWidth.Text)

        ResizeHeight.Text = "" & CInt(Math.Truncate(width / ratio))
    End Sub

    Protected Sub ResizeHeightChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim ratio As Single = Parse(Of Single)(ImageAspectRatio.Value)
        Dim height As Integer = Parse(Of Integer)(ResizeHeight.Text)

        ResizeWidth.Text = "" & CInt(Math.Truncate(height * ratio))
    End Sub

    Protected Sub ResizeImage(ByVal sender As Object, ByVal e As EventArgs)
        Dim width As Integer = Ckeditor_Util.Parse(Of Integer)(ResizeWidth.Text)
        Dim height As Integer = Ckeditor_Util.Parse(Of Integer)(ResizeHeight.Text)

        Dim img As Ckeditor_ImageMedia = Ckeditor_ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue))
        img.Resize(width, height)
        File.Delete(FileImageFolder + ImageList.SelectedValue)
        File.WriteAllBytes(FileImageFolder + ImageList.SelectedValue, img.ToByteArray())

        ResizeMessage.Text = "Image successfully resized!"
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
        If IsImage(UploadedImageFile.FileName) Then
            Dim filename As String = UniqueFilename(UploadedImageFile.FileName)
            UploadedImageFile.SaveAs(FileImageFolder & filename)

            Dim data As Byte() = Ckeditor_ImageMedia.Create(UploadedImageFile.FileBytes).Resize(960, Nothing).ToByteArray()
            Dim file__1 As FileStream = File.Create(FileImageFolder & filename)
            file__1.Write(data, 0, data.Length)
            file__1.Close()

            BindImageList()
            ImageList.SelectedValue = filename
            SelectImage(Nothing, Nothing)
        End If
    End Sub

    Protected Sub Clear(ByVal sender As Object, ByVal e As EventArgs)
        Session.Remove("viewstate")
    End Sub

    'util methods
    Private Function IsImage(ByVal file As String) As Boolean
        Return file.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase) OrElse file.EndsWith(".gif", StringComparison.CurrentCultureIgnoreCase) OrElse file.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase)
    End Function

    Protected Function UniqueFilename(ByVal filename As String) As String
        Dim newfilename As String = filename

        Dim i As Integer = 1
        While File.Exists(FileImageFolder & newfilename)
            newfilename = filename.Insert(filename.LastIndexOf("."c), "(" & i & ")")
            i += 1
        End While

        Return newfilename
    End Function

    Protected Function UniqueDirectory(ByVal directoryname As String) As String
        Dim newdirectoryname As String = directoryname

        Dim i As Integer = 1
        While Directory.Exists(FileImageFolderRoot & newdirectoryname)
            newdirectoryname = directoryname & "(" & i & ")"
            i += 1
        End While

        Return newdirectoryname
    End Function

    'properties
    Protected ReadOnly Property ImageFolderRoot() As String
        Get
            Return ResolveUrl(ConfigurationManager.AppSettings("ImageRoot"))
        End Get
    End Property

    Protected ReadOnly Property FileImageFolderRoot() As String
        Get
            Return Server.MapPath(ImageFolderRoot)
        End Get
    End Property

    Protected Property ImageFolder() As String
        Get
            Return ImageFolderRoot & Convert.ToString(ViewState("folder"))
        End Get
        Set(ByVal value As String)
            ViewState("folder") = value
        End Set
    End Property

    Protected ReadOnly Property FileImageFolder() As String
        Get
            Return Server.MapPath(ImageFolder)
        End Get
    End Property

End Class